//
//  GUserAccount.swift
//  sinaWeiBoAI
//
//  Created by Z.J on 16/3/22.
//  Copyright © 2016年 Z.J. All rights reserved.
//

import UIKit

/// 全局模块,用来保存帐号信息
class GUserAccount: NSObject, NSCoding {

    /// 用于调用access_token，接口获取授权后的access token
    var access_token: String?
    
    // 基本数据类型作为属性不能为可选,使用一个默认值
    /// access_token的生命周期，单位是秒数
    var expires_in: NSTimeInterval = 0{
        didSet{
             // 当KVC给expires_in赋值完成后将expires_in转成NSDate
            expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }

    /// 过期时间,expires_in转成系统的NSDate,expires_in是Double不好来判断过期时间,转成NSDate比较好判断过期时间
    var expiresDate: NSDate?
    /// 当前授权用户的UID
    var uid: String?
    
    /// 使用KVC字典转模型
    init(dict :[String:AnyObject]) {
        // 没有在super.init()之前给属性赋值,属性需要定义为可选
        super.init()
        // 使用KVC赋值
        setValuesForKeysWithDictionary(dict)
    }
    /// 字典中的key在模型中找不到对应的属性,需要重写此方法,才不会崩溃
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        print("key :\(key)")
    }

    /// 归档
    func encodeWithCoder(aCoder: NSCoder)
    {
        aCoder.encodeObject(access_token,forKey: "access_token")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
    }
    
    /// 解档
    required init?(coder aDecoder: NSCoder)
    {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        uid = aDecoder.decodeObjectForKey("uid") as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
    }
}

extension GUserAccount
{
    /// 打印输出 description
    override var description : String
    {
        get{
            let keys = ["access_token", "expires_in", "expiresDate", "uid"]
            
            return dictionaryWithValuesForKeys(keys).description
        }
    }
}
